<?php

namespace App\Http\Middleware;

use App\Kit\RedisKey;
use App\Kit\Token;
use App\Models\AdminModel;
use App\Models\AdminRouteModel;
use App\Models\log\AdminLogModel;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;
use stdClass;

class Admin
{
    public function handle(Request $request, Closure $next)
    {

        $uri = substr($request->path(), 6);
        $noAuth = ['login','pda/login', 'run-test', 'lazada/order', 'lazada/bigbag', 'lazada/update', 'tm/asn', 'tm/notify', 'tm/update', 'lazada/test', 'lazada/check_sign'];
        if(in_array($uri, $noAuth)) {
            return $next($request);
        }

        // 导出临时增加内存
        if(strpos($uri, 'export') !== false){
            ini_set('memory_limit', '1024M');
        }

        $token = base64_decode($request->header('token'));
        $err = [
            'data' => [],
            'message' => '',
            'code' => 400
        ];
        if(empty($token)) {
            return response()->json($err);
        }

        $payload = Token::decodeToken($token);
        if(!$payload) {
            return response()->json($err);
        }

        $storage_token = Token::get_admin_token($payload->data->id);
        if($token != $storage_token) {
            return response()->json($err);
        }

        $info_key = RedisKey::admin_info($payload->data->id);
        $admin = Redis::get($info_key);
        if($admin) {
            $admin = json_decode($admin);
        } else {
            $admin = AdminModel::find($payload->data->id);

            if(!$admin) {
                return response()->json($err);
            }

            $authInfo = $admin->toArray();
            $authInfo['last_login_time'] = $admin->last_login_time;
            Redis::set($info_key, json_encode($authInfo));
        }

        if(!$admin) {
            return response()->json($err);
        }

        $auth = new stdClass;
        $auth->id = $admin->id;
        $auth->account = $admin->account;
        $request->attributes->add(['auth' => $auth]);
        $this->log($request, $admin);
        return $next($request);
    }

    public function log($request, $admin)
    {
        $method = $request->method();
        $uri = $request->getPathInfo();
        $uri = $this->handleUri($uri);

        $params = $request->all();
        $log = new AdminLogModel();
        $log->username = $admin->account;
        $log->method = $method;
        $log->uri = $uri;
        $log->auth_id = $admin->id;
        $log->url = $request->url();
        $log->ip = $request->ip();
        $log->useragent = $request->server('HTTP_USER_AGENT');
        $log->content = json_encode($params);

        if($method != 'GET'){
            $find_route = AdminRouteModel::where('uri', $uri)->where('method', $method)->first();
            if($find_route) {
                $log->title = $find_route->route_name;
                $log->flag = 1;
            }
        }


        $log->save();
    }

    public function handleUri($uri)
    {
        $uri_arr = explode('/', $uri);
        array_shift($uri_arr);
        array_shift($uri_arr);

        // 检查最后一个元素是否为数字索引（数组标识）
        if (is_numeric(end($uri_arr))) {
            array_pop($uri_arr); // 去掉最后一个元素
        }

        return '/' . implode('/', $uri_arr);
    }

}
